import { computed, ComputedRef, defineComponent, onMounted, onUnmounted, reactive, Ref, ref, toRaw } from 'vue';
import { Button, Dialog, Popup, Swipe, SwipeItem, Toast } from 'vant';
import { rejectHomework, rejectReviseHomework } from '@/domain/correction/api/editor';
import Serial from './serial';
import { useImageStore } from '@/domain/correction/hooks/image';
import Reject from './reject';
import router from '../../router';
import { ReqRefuseParam } from '@/domain/correction/types/jobs/jobCorrect';
import { ESubmitType } from '@/domain/correction/types/jobs/homeWork';
import { AnswersID } from '@/domain/correction/types';
import { useCurrectStdStore } from '@/domain/correction/hooks/currectStd';

export default defineComponent({
  name: 'carousel',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    stu_id: {
      type: Boolean,
      default: false
    }
  },
  setup() {
    const store = useImageStore();
    const homeWorkStore = useCurrectStdStore();
    const imageUrlList = computed(() => store.state.images);
    const swipe: Ref<any> = ref(null);
    const getCurrentImageIndex = computed(() => (store.state.activeImageManages ? store.state.currentImageIndex : 1));
    const currentImageIndex = ref(getCurrentImageIndex.value);
    const rejectStatus = ref(false);
    const random = ref(0.5);
    onMounted(() => {
      random.value = Math.random();
    });
    //轮播
    const pre = () => {
      if (swipe.value) swipe.value.prev();
    };
    const next = () => {
      if (swipe.value) swipe.value.next();
    };
    /**设置当前序号 */
    const setCurrent = (num: number) => {
      store.state.currentImageIndex = num;
      if (swipe.value) swipe.value.swipeTo(num - 1);
    };
    /**设置题目序号 */
    const setBySubjectCurrent = (id: AnswersID) => {
      //使用状态，只取调用第一个
      let usedState = false;
      imageUrlList.value.forEach((n, idx) => {
        if (n.id === id && !usedState) {
          if (swipe.value) {
            swipe.value.swipeTo(idx);
            usedState = true;
            store.state.currentImageIndex = idx + 1;
          }
        }
      });
    };
    //设置默认驳回文字
    const radioText = ref('不是本讲内容，讲次交错啦');
    const setRadioText = (name: string) => {
      radioText.value = name;
    };
    //   type ReqRefuseParam = Pick<ReqJobCorrectParam, "commit_id" | "work_id" | "work_type" | "stu_name"> | {
    //     reject_reason: string;
    //     wrong_tests: string;
    // }
    //拒绝
    const rejectHomeworkParam: ComputedRef<ReqRefuseParam> = computed(() => ({
      commit_id: homeWorkStore.state.currentStdHomeWork?.commit!.commit_id!,
      work_id: homeWorkStore.state.homework?.id!,
      work_type: homeWorkStore.state.homework?.type!,
      stu_name: homeWorkStore.state.currentStdHomeWork?.stu_name!,
      reject_reason: radioText.value,
      wrong_tests: homeWorkStore.state.currentStdHomeWork?.wrong_test_ids.map((v) => v.id)?.join(',')
      //homeWorkStore.state.currentStdHomeWork?.wrong_test_ids.filter(val=>val.id)
      // homeWorkStore.state.homeWorkList?.homeWork.test_info.map(val=>val.id).join(',')//试题次序
    }));
    return () => (
      <div class="w-full h-full">
        <Serial current={currentImageIndex.value} setCurrent={setCurrent} setBySubjectCurrent={setBySubjectCurrent}></Serial>
        <div class={'img-contain w-full h-v70 border-gray-200  relative'}>
          <div class={'w-full h-v70 border-gray-200  absolute mt-1'}>
            <Swipe
              ref={(r: any) => (swipe.value = r)}
              autoplay={0}
              initial-swipe={currentImageIndex.value - 1}
              onChange={(val) => {
                currentImageIndex.value = val + 1;
              }}
            >
              {imageUrlList.value.map((node) => (
                <SwipeItem>
                  <img class={'w-full h-v70'} src={node.imgUrl ? node.imgUrl + '?r=' + random.value : node.baseUrl}></img>
                </SwipeItem>
              ))}
            </Swipe>
          </div>
          <i
            class={
              ' text-5xl iconfont icon-shangyidaoti-bukedianji1 text-gray-500 opacity-50 cursor-pointer absolute left-5 top-1/2 transform -translate-y-1/2'
            }
            onClick={pre}
          ></i>
          <i
            class={' text-5xl iconfont icon-xiayidaoti1 cursor-pointer  text-gray-500  opacity-50  absolute right-5 top-1/2 transform -translate-y-1/2'}
            onClick={next}
          ></i>
        </div>
        <div class="w-full fixed bottom-0 pt-5 pb-2  bg-white">
          <div class={'w-full h-r6.3 flex'}>
            <Button
              class={'w-r17 h-r4.8 rounded-r8.5 ml-4 text-r1.6 font-regular'}
              onClick={() => {
                rejectStatus.value = true;
                Dialog.confirm({
                  title: '驳回理由',
                  message: () => <Reject setRadioText={setRadioText}></Reject>
                })
                  .then(async () => {
                    let res;
                    if (homeWorkStore.state.submitType === ESubmitType.frist) {
                      res = await rejectHomework(rejectHomeworkParam.value);
                    } else {
                      res = await rejectReviseHomework(rejectHomeworkParam.value);
                    }

                    if (res.code === 0) {
                      Toast.success('驳回成功');
                      window.history.back();
                    }
                  })
                  .catch(() => {});
              }}
              plain
              type="primary"
            >
              驳回
            </Button>
            <Button
              class={'w-r17 h-r4.8 rounded-r8.5 ml-4 text-r1.6 font-regular'}
              disabled={!store.state.hasCurrect}
              plain
              type="primary"
              onClick={() => {
                homeWorkStore.state.remarkStatus = true;
              }}
            >
              点评打分
            </Button>
          </div>
        </div>
      </div>
    );
  }
});
